import { createStore, applyMiddleware, compose } from 'redux';
import thunk from 'redux-thunk';
import makeRootReducer from './reducers'

// let storeKey = 'zone_storage';

let persistStorage;

//  app js version detection,
//  clean persistStorage and reload if app updated 
try {
    if (process.env.NODE_ENV === 'production') {
        let currentVersion = localStorage.vczone_version;
        let newVersion = Array.prototype.filter
            .call(
                document.getElementsByTagName('script'), 
                script => script.src.includes('main.')
            )[0].src.match(/main\.(.+)\.chunk\.bundle.js/)[1]; //  get script src, main js hash code
    

        //  detect version
        if (currentVersion !== newVersion) {
            localStorage.clear();
            //  update app version
            localStorage.vczone_version = newVersion;
            window.location.reload();
        }
    }
} catch(e) {
}

const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;

const store = createStore(
    makeRootReducer(),
    persistStorage || {},
    composeEnhancers(
        applyMiddleware(thunk)
    ),
)
store.asyncReducers = {}

store.subscribe((state) => {
    // localStorage[storeKey] = JSON.stringify(store.getState());
});

export default store;
